package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.http.okhttp.HttpTask;
import com.lib.util.ScreenUtil;
import com.lib.util.ToastUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.action.AddVehicleAction;
import com.qbw.app.databinding.VehicleActivityFittingsTboxScanBinding;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.util.FlashLightUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.main.activity.MainActivity;
import com.qbw.app.module.scan.camera.CameraManager;
import com.qbw.app.module.scan.decoding.CaptureActivityHandler;
import com.qbw.app.module.scan.decoding.InactivityTimer;
import com.qbw.app.module.scan.view.ViewfinderView;
import com.qbw.app.module.user.activity.UserLoginRegistActivity;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.core.observable.ObservableBoolean;
import com.qbw.core.observable.ObservableInt;
import com.qbw.core.util.StringUtil;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.jpush.android.api.JPushInterface;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 车辆配件-tbox扫描
 * @author xiansx
 * @date 2020-08-13
 */
public class VehicleBindByScanActivity extends CommonActivity<VehicleActivityFittingsTboxScanBinding> implements SurfaceHolder.Callback , QRCodeView.Delegate{

    public static final int TYPE_FROM_DEFAULT = 0;
    /**
     * 注册或者登录之后，没有车辆的情况下，会跳转到此页面
     */
    public static final int TYPE_FROM_NO_VEHICLE = 1;

    private int mType;

//    private Vehicle mVehicle;
    public static final int REQ_PERMISSION = 1;

    private Handler mUiHandler = new Handler();
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private String photo_path;
    private Bitmap scanBitmap;
    //	private Button cancelScanButton;
    // private String mType;
    private ObservableBoolean mLightOn = new ObservableBoolean();
    private FlashLightUtil mFlashLightUtil;
    //是否打开了灯
    private boolean mIsOpenLight = false;
    /**
     * 扫描的状态
     */
    private ObservableInt mStatus = new ObservableInt();
    private ObservableBoolean mInvalidNet = new ObservableBoolean();

    public static void startActivity(Context context) {
        startActivity(context, TYPE_FROM_DEFAULT);
    }

    public static void startActivity(Context context, int type) {
        Intent intent = new Intent(context, VehicleBindByScanActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_TYPE, type);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_fittings_tbox_scan;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
//        mVehicle = (Vehicle) args.getSerializable(Constant.KEY_VEHICLE);
//        mBinding.title.setSubTitle(mVehicle.getVehicleNick());
        mType = args.getInt(Constant.KEY_TYPE);
        mBinding.title.setSubTitleVisible(true);
        mBinding.title.setListener(this);
        CameraManager.init(getApplication());
        CameraManager.get().setAreaHeight((int) (ScreenUtil.getScreenWidth(this) * 0.43f));
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        mBinding.tvManual.setOnClickListener(this);
        mBinding.ivFlash.setOnClickListener(this);
        mBinding.setFlash(mLightOn);
        mBinding.executePendingBindings();
        mBinding.zxingview.setDelegate(this);
    }

    /**
     * 绑定tbox
     */
    private void fbindDevice(String result) {
        if (!TextUtils.isEmpty(result)) {
            String deviceCode = "";
            String devicePassword = "";
            try {
                deviceCode = StringUtil.getUrlParameter(result, "i", "");
                devicePassword = StringUtil.getUrlParameter(result, "c", "");
            } catch (Exception e) {
            }

            if(!TextUtils.isEmpty(deviceCode) &&
                    !TextUtils.isEmpty(devicePassword))
                mGeneralManager.getRequestManager()
                        .getVehicleRequest()
                        .addVehicleNm(deviceCode, devicePassword,
                                this)
                        .execute();
        }
    }

    private void reStartScan() {
        if (handler != null) {
            handler.sendEmptyMessage(R.id.restart_preview);
        }
    }

    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 获取新的大小
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0) sampleSize = 1;
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        com.qbw.app.module.scan.decoding.RGBLuminanceSource source = new com.qbw.app.module.scan.decoding.RGBLuminanceSource(
                scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(bitmap1, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_VEHICLE_ADD_V)) {
            Vehicle vehicle = (Vehicle) httpTask.getExtraParam("newVehicle");
            ActionManager.getInstance()
                    .triggerAction(new AddVehicleAction(vehicle));
            closeLoadingDialog();
            ToastUtil.showToast(this,R.string.vehicle_successfully_added, Toast.LENGTH_LONG);
//            if (mType == TYPE_FROM_NO_VEHICLE) {
//                MainActivity.start(this);
//            }
            MainActivity.start(this);
            finish();
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_VEHICLE_ADD_V)) {
//            UniversalToastUtil.showFailedIconToast(HttpRequestUtil.getMessage(errorCode, message));
            ToastUtil.showToastLong(this,message);
        }
        mBinding.zxingview.stopCamera();
        mBinding.zxingview.stopSpotAndHiddenRect();
        mBinding.zxingview.startCamera();
        mBinding.zxingview.startSpotAndShowRect();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        startScanner();
//        String[] perms = new String[]{Manifest.permission.CAMERA};
//        if (EasyPermissions.hasPermissions(this, perms)) {
//            //do nothing
//        } else {
//            EasyPermissions.requestPermissions(this,
//                    ResUtil.getString(R.string.rotional_camera),
//                    REQ_PERMISSION,
//                    perms);
//        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBinding.zxingview.startCamera();
        mBinding.zxingview.startSpotAndShowRect();
    }



    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (handler != null) {
//            handler.quitSynchronously();
//            handler = null;
//        }
//        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        /*if (mLightOn.isValue()) {
            mFlashLightUtil.tryLightSwitch(this, false);
        }*/
//        mUiHandler.removeCallbacksAndMessages(null);
//        inactivityTimer.shutdown();
        super.onDestroy();
        mBinding.zxingview.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (TextUtils.isEmpty(resultString)) {
            UniversalToastUtil.showToast("Scan failed!");
        } else {
            /*Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("result", resultString);
            // 不能使用Intent传递大于40kb的bitmap，可以使用一个单例对象存储这个bitmap
            //            bundle.putParcelable("bitmap", barcode);
            resultIntent.putExtras(bundle);
            this.setResult(RESULT_OK, resultIntent);*/
            //Toast.makeText(this, resultString, Toast.LENGTH_SHORT).show();
            //mUserPresenter.addCar(mCarName, 1, resultString);
            //Go.InstallObdActivity().from(this).go();

            //ActionManager.getInstance().triggerAction(new ScanAction(mType, resultString));
            //finish();
//            fbindDevice(resultString);
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
        mFlashLightUtil = new FlashLightUtil(CameraManager.get().getCamera());
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(),
                        file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.tv_manual) {
            VehicleBindActivity.startActivity(this);
            this.finish();
        } else if (v.getId() == R.id.iv_flash) {
//            mLightOn.setValue(!mLightOn.isValue());
//            mFlashLightUtil.tryLightSwitch(this, mLightOn.isValue());
            // 打开或者关闭灯
            if (!mIsOpenLight) {
                mBinding.zxingview.openFlashlight();
                mBinding.ivFlash.setImageResource(R.drawable.scan_flashligth_open);
            } else {
                mBinding.zxingview.closeFlashlight();
                mBinding.ivFlash.setImageResource(R.drawable.scan_flashligth_close);
            }
            mIsOpenLight = !mIsOpenLight;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        }
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        mBinding.zxingview.startSpot();
        if (!TextUtils.isEmpty(result)) {
            String deviceCode = "";
            String devicePassword = "";
            try {
                deviceCode = StringUtil.getUrlParameter(result, "i", "");
                devicePassword = StringUtil.getUrlParameter(result, "c", "");
            } catch (Exception e) {
            }

            if(!TextUtils.isEmpty(deviceCode) &&
                    !TextUtils.isEmpty(devicePassword)) {
                Vehicle vehicle = new Vehicle();
                vehicle.setDeviceCode(deviceCode);
                vehicle.setDevicePassword(devicePassword);

                mGeneralManager.getRequestManager()
                        .getVehicleRequest()
                        .addVehicleNm(deviceCode, devicePassword,
                                this)
                        .addExtraParam("newVehicle", vehicle)
                        .execute();
            }
        }

    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {

    }

    @Override
    public void onLeftAreaClick() {
        if (mType == TYPE_FROM_NO_VEHICLE) {
            // 注销账号
            mGeneralManager.getRequestManager()
                    .getCommonRequest()
                    .stopPush(JPushInterface.getRegistrationID(this), null)
                    .execute();
            mGeneralManager.getUserManager().logout();

            UserLoginRegistActivity.start(this);
        }
        super.onLeftAreaClick();
    }

    @Override
    public void onBackPressed() {
        onLeftAreaClick();
    }

}
